package sk.marek.barak.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import sk.marek.barak.client.UserThought;
import sk.marek.barak.shared.Util;

public class ThoughtGAEDAO implements ThoughtDAO {

	@Override
	public List<UserThought> getUserThoughts(String userID) {
		return getAllThoughts(userID);
	}

	@Override
	public UserThought saveThought(String text) {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		Key parentKey = KeyFactory.createKey("User",user.getUserId());
		Entity entity = new Entity("UserThought",parentKey);
		Date date = new Date();
		entity.setProperty("text", text);
		entity.setProperty("date", date.toString());
		entity.setProperty("user",user.getUserId());
		Util.persistEntity(entity);
		
		UserThought thought = new UserThought(KeyFactory.keyToString(entity.getKey()));
		Key userInfoKey = KeyFactory.createKey("UserInfo", user.getUserId());
		Entity userInfo = Util.findEntity(userInfoKey);
		if(userInfo==null)
			thought.setUser("Anonym");
		else
			thought.setUser(userInfo.getProperty("nickName").toString());
		thought.setDate(date);
		thought.setText(text);
		thought.setUserId(user.getUserId());	
		
		return thought;
	}
	
	
	
	private List<UserThought> getAllThoughts(String userID){
		Key parentKey = KeyFactory.createKey("User",userID);
		Iterable<Entity> entities = Util.listChildren("UserThought", parentKey);
		List<UserThought> list = new ArrayList<UserThought>();
		
		for(Entity en : entities){
			UserThought thought = new UserThought(KeyFactory.keyToString(en.getKey()));
			thought.setDate(new Date(en.getProperty("date").toString()));
			thought.setText(en.getProperty("text").toString());
			Key userKey = KeyFactory.createKey("UserInfo",en.getProperty("user").toString());
			Entity user = Util.findEntity(userKey);
			if(user==null)
				thought.setUser("Anonym");
			thought.setUser(user.getProperty("nickName").toString());
			list.add(thought);
			}	
		return list;
		}

	@Override
	public void deleteThought(String key) {
		Util.deleteEntity(KeyFactory.stringToKey(key));
		
	}

	@Override
	public List<UserThought> getUsersThought(List<String> usersID) {
		List<UserThought> thoughts = new ArrayList<UserThought>();
		for(String id : usersID){
			thoughts.addAll(getAllThoughts(id));
		}
		return thoughts;
	}
}
